package com.adee.netty.lengthfieldbased;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class MessageHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf)msg;
            int len = buf.readInt();
            byte[] contentBytes = new byte[len];
            buf.readBytes(contentBytes);
            String jsonStr = new String(contentBytes, StandardCharsets.UTF_8);
            log.debug("json:{}", jsonStr);
            Message message = JSON.parseObject(jsonStr, Message.class);
            log.info("接受到消息：{}", message);
        } else {
            log.warn("接收到的消息不是ByteBuf类型");
        }
    }
}
